<?php
// +----------------------------------------------------------------------
// | Copyright (c) 2018-2018 http://www.donglixia.net All rights reserved.
// +----------------------------------------------------------------------
// | Author: 十万马 <962863675@qq.com>
// +----------------------------------------------------------------------
// | DateTime: 2018-02-09 16:17
// +----------------------------------------------------------------------

namespace app\admin_fussen\controller;

use app\admin_fussen\model\Article as ArticleModel;
use app\admin_fussen\model\ArticleCat;
use app\admin_fussen\model\ArticleExtCat;
use app\admin_fussen\model\BasicAddress;
use app\admin_fussen\model\BasicInfo as BasicInfoModel;
use think\Db;
use think\Request;
use think\Session;

class Article extends Base
{
    public function __construct(Request $request = null)
    {
        parent::__construct($request);
        $this->currentModel = new ArticleModel();//实例化当前模型
    }

    /**
     * 信息中心
     */
    public function index()
    {
        $this->renderData(205);//渲染数据，信息中心cat_type=205
        return $this->fetch('index');
    }

    /**
     * 列表页，获取数据
     * @return mixed
     */
    public function getDataList()
    {
        $map = $this->getDataListMap();
        return $this->currentModel->where($map)->order('sort_num asc, art_id desc')->layTable(['cat_name','level_text','public_date']);
    }

    private function getDataListMap()
    {
        $param = $this->request->param();
        if (!empty($param['cat_type'])) {
            $cat_ids = Db::name('article_cat')->where('cat_type', $param['cat_type'])->column('cat_id');
            $map['cat_id'] = ['in', $cat_ids];//大板块
        }
        if (!empty($param['cat_id'])) {
            $map['cat_id'] = ['in', get_child_ids($param['cat_id'], 'article_cat')];//栏目，包含子栏目
        }
        if (!empty($param['title'])) {
            $map['title'] = ['like', '%' . $param['title'] . '%'];//标题
        }
        if (!empty($param['level'])) {
            $map['level'] = $param['level'];//推荐等级
        }
        if (!empty($param['public_begin']) && !empty($param['public_end'])) {
            $map['public_time'] = ['between', [strtotime($param['public_begin']),strtotime($param['public_end'])]];//公布时间
        }

        $map['language'] =  Session::get('config.language');
        return $map;
    }

    public function edit()
    {
        $param = $this->request->param();
        $art_id = !empty($param['art_id']) ? $param['art_id'] : '';
        if (!empty($art_id)) {
            //获取当前文章信息
            $data = $this->currentModel->where('art_id', $art_id)->field(true)->field('public_time as public_date_hh_ii_ss')->find();
            if (empty($data)) {
                $this->error('信息不存在');
            }
            $data = $data->toArray();
            $data['cat_type'] = Db::name('article_cat')->where('cat_id', $data['cat_id'])->value('cat_type');
            $this->assign('data', $data);
        }

        /*获取文章推荐等级*/
        $BasicInfo = new BasicInfoModel();
        $levelList = $BasicInfo->getBasicList('article', 'AA');
        $this->assign('levelList' ,$levelList);

        //获取栏目下拉列表
        $map = [];
        $curr_cat_id = 0;
        if (!empty($data['cat_id'])) {
            $map['cat_type'] = $data['cat_type'];
            $curr_cat_id = $data['cat_id'];
        }
        $catList = $this->currentModel->getCatOptionTree($map, $curr_cat_id);
        $this->assign('catList' , $catList);

        //获取扩展栏目下拉列表
        $map = [];
        $curr_cat_ext = !empty($data['art_id']) ? Db::name('article_ext_cat')->where('art_id', $data['art_id'])->column('cat_id') :[];
        if (!empty($data['cat_type'])) {
            $map['cat_type'] = $data['cat_type'];
        }
        $catExtList = $this->currentModel->getCatExtOptionTree($map, $curr_cat_ext);
        $this->assign('catExtList' , $catExtList);

        //获取版块下拉列表
        $basicList = (new ArticleCat())->getBasicList(['cat_code'=>'article']);
        $this->assign('basicList', $basicList);

        return $this->fetch();
    }

    /**
     * 保存
     */
    public function save()
    {
        $param = $this->request->param();
        if (empty($param)) {
            $this->error('没有需要保存的数据！');
        }
        //默认排序为1
        $param['sort_num'] = !empty($param['sort_num']) ? $param['sort_num'] : 1;
        //验证数据
        $result = $this->validate($param, 'Article');
        if ($result !== true) {
            $this->error($result);
        }
        try{
            //图片不为空，开始处理图片
            if (!empty($param['img_url'])) {
                $old = !empty($param['art_id']) ? Db::name('article')->where('art_id', $param['art_id'])->value('img_url') : '';
                if (empty($old) || $param['img_url'] != $old) {
                    $param['img_url'] = current(imgTempFileMove([$param['img_url']], 'admin_fussen/images/article/'));//从临时文件夹移动图片
                    if (!empty($param['art_id'])) {
                        $count = Db::name('article')->where('img_url', $old)->count();//编辑且换图，则删除旧图片
                        //若其他地方没使用该旧图片，则删除
                        if ($count == 1){
                            delete_file($old);
                        }
                    }
                }
            }

            $this->currentModel->save($param);
            if (isset($param['cat_id_ext'])) {
                $ArticleExtCat = new ArticleExtCat();
                $ArticleExtCat->where('art_id', $this->currentModel->art_id)->delete();

                $cat_ext = [];
                $cat_id_arr = explode(',', $param['cat_id_ext']);
                foreach ($cat_id_arr as $k=>$v) {
                    if (!empty($v)) {
                        $cat_ext[$k]['art_id'] = $this->currentModel->art_id;
                        $cat_ext[$k]['cat_id'] = $v;
                    }
                }
                if (!empty($cat_ext)) {
                    $ArticleExtCat->saveAll($cat_ext);
                }
            }
        } catch (\Exception $e) {
            $msg = !empty($this->currentModel->getError()) ? $this->currentModel->getError() : $e->getMessage();
            save_error_log($msg.' ['.$e->getFile().':'.$e->getLine().']');
            $this->error($msg);
        }

        $this->success('保存成功！', 'edit?art_id='.$this->currentModel->art_id);
    }

    /**
     * 获取栏目下拉列表
     */
    public function getCatListOptionTree()
    {
        $param = $this->request->param();
        $list = [];
        try {
            $map = [];
            $curr_cat_id = !empty($param['cat_id']) ? $param['cat_id'] : 0;
            if (!empty($param['cat_type'])) {
                $map['cat_type'] = $param['cat_type'];
            }

            $list['table_tree'] = $this->currentModel->getCatTableTree($map);
            $list['option_tree'] = $this->currentModel->getCatOptionTree($map, $curr_cat_id);
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }
        $this->success('获取成功', null, $list);
    }

    /**
     * 前端首页
     * @return mixed
     */
    public function homePage()
    {
        $this->renderData(211);//渲染数据，前端首页cat_type=211
        return $this->fetch('index');
    }

    /**
     * 活动中心
     */
    public function activity()
    {
        $this->renderData(206);//渲染数据，活动中心cat_type=206
        return $this->fetch('index');
    }

    /**
     * 品牌中心
     */
    public function brand()
    {
        $this->renderData(209);//渲染数据，品牌中心cat_type=209
        return $this->fetch('index');
    }

    /**
     * 葡萄酒学院
     */
    public function college()
    {
        $this->renderData(207);//渲染数据，葡萄酒学院cat_type=207
        return $this->fetch('index');
    }

    /**
     * 爱心基金
     */
    public function fund()
    {
        $this->renderData(212);//渲染数据，爱心基金cat_type=212
        return $this->fetch('index');
    }

    /**
     * 关于我们
     */
    public function about()
    {
        $this->renderData(208);//渲染数据，关于我们cat_type=208
        return $this->fetch('index');
    }

    /**
     * 网站指南/常见问题
     */
    public function guide()
    {
        $this->renderData(210);//渲染数据，常见问题cat_type=210
        return $this->fetch('index');
    }

    /**
     * 渲染数据，公共方法
     * @param $cat_type array 按版块id搜索
     * @return mixed
     */
    private function renderData($cat_type = [])
    {
        //栏目
        $catList = $this->currentModel->getCatOptionTree(['cat_type'=>$cat_type]);
        $this->assign('catList', $catList);
        $this->assign('cat_type', $cat_type);

        /*获取推荐等级*/
        $BasicInfo = new BasicInfoModel();
        $levelList = $BasicInfo->getBasicList('article', 'AA');
        $this->assign('levelList' ,$levelList);
    }

    /**
     * 首彩版图，列表页
     */
    public function domainIndex()
    {
        //获取省份列表
        $provinceList = $this->getRegion(0);
        $this->assign('provinceList', $provinceList);

        return $this->fetch();
    }

    /**
     * 首彩版图，获取数据
     */
    public function getDomainList()
    {
        $param = $this->request->param();
        $map = [];
        if (!empty($param['province'])) {
            $map['province'] = $param['province'];//省份
        }
        $map['type'] = 2;
        $BasicAddress = new BasicAddress();
        return $BasicAddress->where($map)->order('sort_num asc')->layTable(['province_text','city_text','district_text']);
    }

    /**
     * 首彩版图，编辑
     * @param $id
     * @return mixed
     */
    public function domainEdit($id)
    {
        $BasicAddress = new BasicAddress();
        if (!empty($id)) {
            $data = $BasicAddress->where('id', $id)->field(true)
                ->field('province as province_text,city as city_text,district as district_text')
                ->find();
            if (empty($data)) {
                $this->error('信息不存在');
            }
            $data = $data->toArray();
            $this->assign('data', $data);

            //获取城市列表
            $cityList = $this->getRegion($data['province']);
            $this->assign('cityList', $cityList);

        }

        //获取省份列表
        $provinceList = $this->getRegion(0);
        $this->assign('provinceList', $provinceList);

        return $this->fetch();
    }

    /**
     * 保存
     */
    public function domainSave()
    {
        $param = $this->request->param();
        if (empty($param)) {
            $this->error('没有需要保存的数据！');
        }
        //默认排序为1
        $param['sort_num'] = !empty($param['sort_num']) ? $param['sort_num'] : 1;
        $BasicAddress = new BasicAddress();
        try{
            $BasicAddress->save($param);
        } catch (\Exception $e) {
            $msg = !empty($BasicAddress->getError()) ? $BasicAddress->getError() : $e->getMessage();
            save_error_log($msg.' ['.$e->getFile().':'.$e->getLine().']');
            $this->error($msg);
        }

        $this->success('保存成功！', 'domainEdit?id='.$BasicAddress->id);
    }

    /**
     * 保存
     */
    public function domainDel()
    {
        $param = $this->request->param();
        $BasicAddress = new BasicAddress();
        try{
            $BasicAddress->where('id', $param['id'])->delete();
        } catch (\Exception $e) {
            $msg = !empty($BasicAddress->getError()) ? $BasicAddress->getError() : $e->getMessage();
            save_error_log($msg.' ['.$e->getFile().':'.$e->getLine().']');
            $this->error($msg);
        }

        $this->success('删除成功！');
    }

    /**
     * 根据pid 获取下拉列表，省市区三级联动
     * @param $pid
     * @return false|\PDOStatement|string|\think\Collection
     * @throws \think\exception\DbException
     */
    public function getRegion($pid = 0)
    {
        $pid = !empty($pid) ? $pid : 0;
        return Db::name('basic_region')->where('parent_id', $pid)->field('id,area_name,area_code')->select();
    }
}

